package com.example.tnot.Teacher.CoursePart.CourseInternal.CourseDetailHome.Activity.PopUpWindowFragment.ClockIn;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.example.tnot.R;
import com.example.tnot.Util.popupwindow.WheelDateTimePickerPopup;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

public class ClockInHomeFragment extends Fragment {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private String mParam1;
    private String mParam2;
    ImageView back;
    View view;
    Button btn_start_sign_in;
    RadioGroup RadioGroup;
    String classname;
    EditText et_title;
    private TextView tv_classlabel,tv_clasName;
    private Calendar selectedReturnDate;
    private WheelDateTimePickerPopup dateTimePickerPopup;
    private ImageView iv_startTime,iv_endTime;
    private LinearLayout ll_startTime,ll_endTime,ll_select_class;
    private TextView tv_startTime,tv_endTime;
    private boolean isStartTimeSelected = false,isEndTimeSelected = false;

    public ClockInHomeFragment() {
    }

    public static ClockInHomeFragment newInstance(String param1, String param2) {
        ClockInHomeFragment fragment = new ClockInHomeFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view =  inflater.inflate(R.layout.course_clock_in_home_fragment, container, false);
        InitViews();
        //设置点击监听
        SetListener();

        return view;
    }
    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        // 在 onViewCreated 中处理 NavController 相关逻辑
        setupNavControllerListener();
    }


    private void InitViews() {
        et_title = view.findViewById(R.id.et_title);
        back = view.findViewById(R.id.back);
        btn_start_sign_in = view.findViewById(R.id.btn_start_sign_in);
        iv_startTime = view.findViewById(R.id.iv_startTime);
        iv_endTime = view.findViewById(R.id.iv_endTime);
        ll_startTime = view.findViewById(R.id.ll_startTime);
        ll_endTime = view.findViewById(R.id.ll_endTime);
        ll_select_class = view.findViewById(R.id.ll_select_class);
        tv_startTime = view.findViewById(R.id.tv_startTime);
        tv_endTime = view.findViewById(R.id.tv_endTime);
        tv_classlabel = view.findViewById(R.id.tv_classlabel);
        tv_clasName = view.findViewById(R.id.tv_clasName);
    }
    private void SetListener() {
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NavController navController = Navigation.findNavController(v);
                navController.navigateUp();
            }
        });

        btn_start_sign_in.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NavController navController = Navigation.findNavController(v);
                navController.navigate(R.id.action_clockInHomeFragment_to_finishClockInFragment);
            }
        });
        ll_startTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ll_startTime.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        isStartTimeSelected = !isStartTimeSelected;
                        showDateTimePickerPopup(v,tv_startTime);
                        if(isStartTimeSelected){
                            iv_startTime.setImageResource(R.drawable.pull_down);
                        }else {
                            iv_startTime.setImageResource(R.drawable.pull_up);
                        }
                    }
                });
            }
        });
        ll_endTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isEndTimeSelected = !isEndTimeSelected;
                showDateTimePickerPopup(v,tv_endTime);
                if(isEndTimeSelected){
                    iv_endTime.setImageResource(R.drawable.pull_down);
                }else {
                    iv_endTime.setImageResource(R.drawable.pull_up);
                }
            }
        });
        ll_select_class.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NavController navController = Navigation.findNavController(v);
                navController.navigate(R.id.action_clockInHomeFragment_to_selectClassFragment);
            }
        });

    }
    private void showDateTimePickerPopup(View anchorView, TextView click) {
        // 使用 requireActivity() 获取 Fragment 的 Activity Context
        dateTimePickerPopup = new WheelDateTimePickerPopup(requireActivity(), anchorView);

        // 设置当前选择的日期时间（如果有）
        if (selectedReturnDate != null) {
            dateTimePickerPopup.setSelectedDateTime(selectedReturnDate);
        }

        // 设置日期时间选择监听器
        dateTimePickerPopup.setOnDateTimeSelectedListener(new WheelDateTimePickerPopup.OnDateTimeSelectedListener() {
            @Override
            public void onDateTimeSelected(Calendar selectedDateTime) {
                selectedReturnDate = selectedDateTime;
                updateReturnDateDisplay(click);
            }
        });

        // 显示 PopupWindow
        dateTimePickerPopup.show();
    }

    private void updateReturnDateDisplay(TextView  click) {
        if (selectedReturnDate != null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm", Locale.getDefault());
            String TimedateString = sdf.format(selectedReturnDate.getTime());
            click.setText(TimedateString);
            click.setTextColor(getResources().getColor(android.R.color.black));
        }
    }
    //处理返回来的班级名称
    private void setupNavControllerListener() {
        try {
            // 使用 view 来获取 NavController，保持一致性
            NavController navController = Navigation.findNavController(view);
            if (navController.getCurrentBackStackEntry() != null) {
                navController.getCurrentBackStackEntry()
                        .getSavedStateHandle()
                        .getLiveData("selectedClass")
                        .observe(getViewLifecycleOwner(), className -> {
                            if (className != null) {
                                //classname就是上一个SelectClassFragment获取到的班级名称
                                classname = (String) className;
                                Log.d("classname", classname);
                                FinishCLassName();
                            }
                        });
            }
        } catch (Exception e) {
            Log.e("quickAnswerHomeFragment", "Error setting up NavController listener", e);
        }
    }

    private void FinishCLassName() {
        //修改提醒样式
        tv_classlabel.setText("已选择班级");
        tv_classlabel.setTextColor(getResources().getColor(R.color.colorPrimary));
        // 显示班级名称
        tv_clasName.setVisibility(View.VISIBLE);
        tv_clasName.setText(classname);
    }
}